import java.util.*;

public class Main {
    static int[] f, a;
    static int n;

    static int dfs(int x) {
        if(f[x] != 0) return f[x];

        // 两边都比自己大,
        if(a[(x+n-1) % n] >= a[x] && a[(x+1) % n] >= a[x] )
            return f[x] = 1;

        int v = 0;

        // 
        if(a[(x+n-1)% n] < a[x])
            v = dfs((x+n-1)% n);

        if(a[(x+1)% n] < a[x])
            v = Math.max(v, dfs((x+1)%n));

        return f[x] = v + 1;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();       // 用例
        while(T-- > 0) {
            n = sc.nextInt(); // 人数
            a = new int[n];

            f = new int[n];   // 存放结果

            for(int i=0; i < n; i++)
                a[i] = sc.nextInt();

            for(int i=0; i < n; i++)
                dfs(i);

            long res = 0L;
            for(int i=0; i < n; i++)
                res = res + f[i];

            System.out.println(res);
        }
    }
}
